package com.movisol.messengercommunicator.asynctasks;

import android.os.AsyncTask;
import android.widget.Toast;

import com.movisol.messengercommunicator.controllers.CommunicatorController;
import com.movisol.messengercommunicator.data.Conversation;
import com.movisol.messengercommunicator.helper.MessengerCommunicatorHelper;
import com.movisol.messengerprofileservice.helpers.MessengerProfileHelper;
import com.movisol.messengerprofileservice.interfaces.errorcodes.SaveUserProfileErrorCodes;
import com.movisol.tools.HelperUtils;

/**
 * Asynchronous gets the messages list of the selected conversation
 * @author Antonio Santiago
 *
 */
public class AsyncGetMessagesList extends AsyncTask<Conversation, Void, Boolean> {
	
	private CommunicatorController cc = CommunicatorController.getInstance();

	@Override
	protected Boolean doInBackground(Conversation...params) {

		if(params[0] != null)
		{
			
			String conversId = MessengerProfileHelper.generateSignature(MessengerCommunicatorHelper.generateConversationId(((Conversation)params[0]).getContacts()) + HelperUtils.getConfigParam("ChatSecretPhrase", cc.getContext()));
			
			String result = cc.getMessageList(conversId);
			
			cc.setCommunicatorUri4Messages(MessengerCommunicatorHelper.parseXMLConversationMessagesToObject(result));
			
			//Cachear conversationURI
			if(cc.getCommunicatorUri4Messages() != null)
				cc.writeMessageUriToFile( ((Conversation)params[0]).getConversationId() );
			
			return true;
		}
		
		return false;
	}

	@Override
	protected void onPostExecute(Boolean result) {
		super.onPostExecute(result);

		if(result)
		{
			if(cc.getMessagesCache() != null)
				new AsyncLoadMessagesList().execute();
			else
			{
			    HelperUtils.LogE(getClass(), "cc.getMessagesCache() is NULL");
			    HelperUtils.showToastMessage(cc.getContext(), SaveUserProfileErrorCodes.getErrorByCode(SaveUserProfileErrorCodes.INTERNAL_ERROR), Toast.LENGTH_LONG);
			}
		}
		else
		{
			HelperUtils.LogE(getClass(), null);
		}
		
	}
}
